# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import logging
import os
import shutil

from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseServerError, HttpResponseNotFound, Http404, HttpResponseRedirect, \
    HttpResponseBadRequest, HttpResponseForbidden
from django.template import RequestContext
from django.template.loader import get_template
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import requires_csrf_token
from wenlincms.conf import settings
from wenlincms.utils.views import render

from mainsys.settings import PROJECT_ROOT

add_log = logging.getLogger('search')


# 单独的静态html页面，可使用内置template_tag
def systatichtmls(request, html_name):
    context = {}
    templates = [u"static_htmls/statichtmls", "static_htmls/" + html_name + ".html"]
    return render(request, templates, context)


# admin后台用的清除缓存按钮
@login_required
@never_cache
def delcache(request):
    try:
        from mainsys.settings import CACHES
        if CACHES["default"]["BACKEND"].split(".")[-1] == "FileBasedCache":
            from mainsys.settings import CACHE_ROOT
            filelist = os.listdir(CACHE_ROOT)
            for f in filelist:
                filepath = os.path.join(CACHE_ROOT, f)
                if os.path.isfile(filepath):
                    os.remove(filepath)
                elif os.path.isdir(filepath):
                    shutil.rmtree(filepath, True)
        elif CACHES["default"]["BACKEND"].split(".")[-1] == "RedisCache":
            from django_redis import get_redis_connection
            get_redis_connection("default").flushdb()
    except Exception:
        pass
    # 下面判断代码是否有改动，重新加载代码
    try:
        import uwsgi
        from wlapps.utils import code_changed
        if code_changed():
            uwsgi.reload()
    except Exception:
        pass
    return HttpResponse('<script>alert("全站缓存清除成功");window.history.back();</script>')


# admin后台用的清除缓存按钮
@login_required
@never_cache
def Mysql2ES(request):
    try:
        print os.system("pwd")
        os.system("python MysqlToES/Mysql_2_ES.py")
    except Exception:
        pass
    return HttpResponse('<script>alert("数据同步成功");window.history.back();</script>')


@requires_csrf_token
def page_not_found(request, template_name="errors/404.html"):
    """
    扩展 Django 的404页面，启用wenlincms的主题设置
    """
    context = RequestContext(request, {
        "STATIC_URL": settings.STATIC_URL,
        "request_path": request.path,
    })
    try:
        from mainsys.config import WL_THEME
        template_name = WL_THEME + "/" + template_name
    except ImportError:
        pass
    t = get_template(template_name)
    return HttpResponseNotFound(t.render(context))


@requires_csrf_token
def server_error(request, template_name="errors/500.html"):
    """
    扩展 Django 的500错误页面，启用wenlincms的主题设置
    """
    context = RequestContext(request, {"STATIC_URL": settings.STATIC_URL})
    try:
        from mainsys.config import WL_THEME
        template_name = WL_THEME + "/" + template_name
    except ImportError:
        pass
    t = get_template(template_name)
    return HttpResponseServerError(t.render(context))


@requires_csrf_token
def bad_request(request, template_name="errors/400.html"):
    """
    扩展 Django 的400错误页面，启用wenlincms的主题设置
    """
    context = RequestContext(request, {"STATIC_URL": settings.STATIC_URL})
    try:
        from mainsys.config import WL_THEME
        template_name = WL_THEME + "/" + template_name
    except ImportError:
        pass
    t = get_template(template_name)
    return HttpResponseBadRequest(t.render(context))


@requires_csrf_token
def forbidden(request, template_name="errors/403.html"):
    """
    扩展 Django 的403错误页面，启用wenlincms的主题设置
    """
    context = RequestContext(request, {"STATIC_URL": settings.STATIC_URL})
    try:
        from mainsys.config import WL_THEME
        template_name = WL_THEME + "/" + template_name
    except ImportError:
        pass
    t = get_template(template_name)
    return HttpResponseForbidden(t.render(context))


# 在线查看日志文件
@never_cache
def wllog(request, log_name, row_num):
    if request.user.is_superuser:
        log_dir = os.path.join(PROJECT_ROOT, "../mainsys/log/")
        log_file = os.path.join(log_dir, log_name)
        if os.path.isfile(log_file):
            log_file_handle = open(log_file, 'r')
            row_num = int(row_num)
            flines = log_file_handle.readlines()
            lines = []
            count = 0
            for line in reversed(flines):
                # 如果显示有乱码，则采用下面的方法
                # if log_name in ["wechat", ]:
                #     line = line.decode('unicode_escape')
                lines.append(line.rstrip())
                count += 1
                if count >= row_num:
                    break
            log_file_handle.close()

            # 遍历log目录下所有文件
            all_logs = []
            for each_log in os.listdir(log_dir):
                if each_log != "index.html" and os.path.isfile(os.path.join(log_dir, each_log)):
                    all_logs.append(each_log)
            context = {"lines": reversed(lines), "log_name": log_name, "all_logs": all_logs}
            templates = [u"admin/includes/log.html", "admin/includes/log.html"]
            return render(request, templates, context)
        else:
            raise Http404
    else:
        return HttpResponseRedirect("/admin")
